// pages/device/device.js

const app = getApp() //获取应用实例
// import bleDisNetwork from '../../utils/bleDisNetwork'

// const instruct = require('../../utils/tspl')
const request = require('../../util/request')
const instruct = require('../../util/tspl')
// const bleDisNetwork = require('../../util/bleDisNetwork')
import bleDisNetwork from '../../util/bleDisNetwork'
let ctx = null
Page({
  /**
   * 页面的初始数据
   */
  data: {
    blueLists: [],//蓝牙列表
    deviceId: '',
    imageSize: [0, 0],
    notify: "2700c46ba143131981af816414cdbf4b2c88e4664978cbfd33e7ff0073d7714ad1c0d2c4c049fcb7f5", // 返回信号 没使用
    connDevice: '',
    hasLoadPic: false,
    isOK:false,
    searchState:false,
  },

  /*初始化*/
  blueInit: async function () {
    await bleDisNetwork.openBluetooth()
    this.setData({
      // connState: true, 没用
      blueLists: [],
      searchState: false,
      connDevice: '',
      connectInit: false,
      WH: [0, 0]
    })
    let blueLists = []
    this.setData({
      searchState: true
    })
    bleDisNetwork.deviceSearch('', 'name', (device) => {
      console.log('device=====', device)
      blueLists.push(device)
      this.setData({
        blueLists
      })
      console.log(this.data.blueLists,"blueListsblueLists")
    })
  },

  /*连接*/
  connBlue: async function (e) {
    let self = this
    bleDisNetwork.stopSearchBluetooth()
    if (e.currentTarget.dataset.state != '1') {
      wx.showLoading({
        title: '连接中',
        mask: true
      })
      try {
        await bleDisNetwork.connectBluetooth(e.currentTarget.dataset.did)
        wx.showToast({
          title: '成功连接',
          icon: 'success',
        })
        this.setData({
          blueLists: [{
            'name': e.currentTarget.dataset.name,
            'deviceId': e.currentTarget.dataset.did,
            'state': 1
          }],
          searchState: false,
          connDevice: e.currentTarget.dataset.did
        })
        bleDisNetwork.onBLECharacteristicValueChange(this.readBleData)
      } catch (error) {
        wx.showToast({
          title: '连接失败',
          icon: 'error',
        })
        this.setData({
          searchState: false,
        })
        wx.hideLoading()
      } finally {
        wx.hideLoading()
      }
    }
  },

  // 按钮点击事件
  buttonClick(target) {
    let buffer = null
    console.log(target,"targettarget")
    switch (target.currentTarget.dataset.type) {
      case '文字':
        //打印标签内容是根据产品来的
        let tmp = {
          品名:'尼龙扣布',
          订单号:'',
          缸号:'G2503082',
          颜色:'本白',
          色号:'RK8152B-(1)',
          幅宽:'1.4000',
          克重:'22',
          重量:'53.4 KG',
          码数:'1302码',
          批号:'G2503082-1'
        }
        buffer = instruct.textSend(tmp)
        break
      case '产品':
        let tmp1 = {
          产品型号:'TEST12138',
          生产日期:'2025/11/2',
          产品条码:'01021600BEKJ129347',
          产品信息:'这里是产品信息,这里是产品信息,这里是产品信息,这里是产品信息',
        }
        buffer = instruct.textchanpin(tmp1)
        break
      case '条码':
        let tmp2 = {
          产品型号:'123456789',
          产品条码:'123456789',
          产品信息:'123456789'
        }
        buffer = instruct.barcodeSend(tmp2)
        break
      case '二维码':
        
        buffer = instruct.qrcodeSend()
        break
      case '样表':
        buffer = instruct.tableSend()
        break
      case "图片":
        this.chooseImage()
        break
      
    }
    if (buffer) this.writeBleChaValue(buffer)
  },
  chooseImage() {
    var self = this
    if (self.data.hasLoadPic) {
      setTimeout(function () {
        self.imagePrint()
      }, 500)
      return
    }
    
    var imgPath = "/assets/logo.png" // 图片地址
    wx.getImageInfo({
      src: imgPath,
      // 固定图高80px（自定义，8的倍数）
      success: (res) => {
        console.log('aa=====')
        self.setData({
          imageSize: [parseInt(res.width * (120 / res.height)), 120]
        })
      },
      fail: () => {
        return
      },
      complete: function () {
        console.log('ccc=====')
        var imageSize = self.data.imageSize
        console.log('self.data.imageSize======', self.data.imageSize)
        const query = wx.createSelectorQuery();
        query.select('#bitmapCanvas2')
          .fields({
            node: true,
            size: true
          })
          .exec((res) => {
            const canvas = res[0].node;
            console.log('canvas=====', canvas)
            let canvasNode = canvas; // 保存canvas节点供后续使用
            ctx = canvas.getContext('2d');

            canvas.width = imageSize[0];
            canvas.height = imageSize[1];

            // 创建图片对象
            const img = canvas.createImage();
            img.src = imgPath;
            img.onload = () => {
              ctx.clearRect(0, 0, imageSize[0], imageSize[1]);
              ctx.drawImage(img, 0, 0, imageSize[0], imageSize[1])
              setTimeout(function () {
                self.data.hasLoadPic = true
                self.imagePrint()
              }, 500)
            }
          })
      }
    })

  },
  // 图片打印
  imagePrint: function () {
    if (!ctx) return;
    var self = this
    var imageSize = self.data.imageSize
    console.log('imagePrint======')
    let data = ctx.getImageData(
      0,
      0,
      imageSize[0],
      imageSize[1],
    )
    console.log('imagePrint======', data)
    // 处理图片
    let buffer = instruct.imageSend({
      imageData: data,
      width: imageSize[0],
      height: imageSize[1]
    })
    if (buffer) {
      console.log('buffer======', buffer)
      self.writeBleChaValue(buffer)
    }
  },

  // 发送蓝牙设备数据
  async writeBleChaValue(bytes) {
    
    const MAX_PACKET = 20; // 每次发送的最大数据包大小
    const totalLen = bytes.length || bytes.byteLength;
    let offset = 0;
    console.log('PrintSend======', bytes.length, bytes.byteLength);
    wx.showLoading({
      title: '发送中',
    })
    while (offset < totalLen) {
      const end = Math.min(offset + MAX_PACKET, totalLen);
      const packet = bytes.slice(offset, end);
      console.log('PrintSend 发送数据:', 'offset:', offset, 'end:', end);
      // 兼容 Uint8Array/ArrayBuffer
      let dataBuffer = packet instanceof Uint8Array ? packet.buffer : packet;
      try {
        let res = await bleDisNetwork.writeBluetoothCharacteristicValue(dataBuffer);
        console.log('sendNext 发送结果:', res);
        offset = end;
      } catch (error) {
        console.error('蓝牙发送失败', error);
        return false;
      }
    }
    wx.hideLoading()
    wx.showToast({
      title: '发送成功',
      duration: 2000,
    })
    return true;
  },




  readBleData(res) {
    console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
    let data = new Uint8Array(res.value)
    let getDeviceOrder = data.slice(0, 3)
    // 读取到的数据，转换16进制字符串
    let getDeviceOrderStr = this.ab2hex(getDeviceOrder.buffer)
    console.log('getDeviceOrderStr=======', getDeviceOrderStr)
  },



  // 转十六进制字符串
  ab2hex: function (buffer) {
    const hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('')
  },



  // 十六进制转字符串
  hexToStr(hex) {
    // 去掉字符串首尾空格
    let trimedStr = hex.trim()
    // 判断trimedStr前两个字符是否为0x，如果是则截取从第三个字符及后面所有，否则返回全部字符
    let rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr
    // 得到rawStr的长度
    let len = rawStr.length
    // 如果长度不能被2整除，那么传入的十六进制值有误，返回空字符
    if (len % 2 !== 0) {
      return ""
    }
    let curCharCode // 接收每次循环得到的字符
    let resultStr = [] // 存转换后的十进制值数组
    for (let i = 0; i < len; i = i + 2) {
      curCharCode = parseInt(rawStr.substr(i, 2), 16)
      resultStr.push(curCharCode)
    }
    // encoding为空时默认为utf-8
    let bytesView = new Uint8Array(resultStr) // 8 位无符号整数值的类型化数组
    // TextEncoder和TextDecoder对字符串和字节流互转  
    let str = new encoding.TextDecoder("gbk").decode(bytesView)
    return str
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    

    // if (options.id) {
    //   this.setData({
    //     deviceId: decodeURIComponent(options.id)
    //   })
    //   console.log("获取连接蓝牙deviceId：", this.data.deviceId)
    //   wx.showLoading({
    //     title: '获取蓝牙信息中......'
    //   })
    //   this.getBLEConnectionStateChange()
    //   this.getBLEDeviceServices()
    // } else {
    //   wx.showToast('非法访问')
    // }
    // wx.setNavigationBarTitle({
    //   title: '(TSPL)',
    // })
  },
  /*终止*/
  blueStop: async function () {
    await bleDisNetwork.stopSearchBluetooth()
    await bleDisNetwork.closeConnectBluetooth(this.data.connDevice)
    this.setData({
      connDevice: '',
      blueLists: [],
      searchState: false,
      connectInit: false,
      WH: [0, 0]
    })
  },

  /*后退*/
  backIndex: function () {
    wx.reLaunch({
      url: '../index/index',
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.blueStop()
  }
})